package com.yang.ddz.netty;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpHeaders;
import org.apache.log4j.Logger;

import java.util.concurrent.ExecutorService;

/**
 * Created by zongx on 2019/12/31.
 */
public class HttpServerRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private static Logger logger = Logger.getLogger(HttpServerRequestHandler.class);

    private final String httpPrefix;

    private ExecutorService httpExecutors;

    public HttpServerRequestHandler(ExecutorService httpExecutors, String httpPrefix) {
        this.httpPrefix = httpPrefix;
        this.httpExecutors = httpExecutors;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
        String uri = msg.getUri();
        if (uri.equalsIgnoreCase("/srws")) {
            //如果请求了WebSocket协议，则增加引用技术，并将它传递给下一个ChannelInboundHandler
            ctx.fireChannelRead(msg.retain());
        } else if (uri.startsWith(httpPrefix)) {
            //判断前端来的url路径是否正确
            JSONObject json = new JSONObject();
            json.put("code", 200);
            json.put("message", "操作成功");

            //获取要进行的操作与json参数
            int index = uri.indexOf("?");
            String op = uri.substring(httpPrefix.length(), index == -1 ? uri.length() : index);
            String param = (index == -1) ? "" : uri.substring(index + 1);
            String body = "";

            //获取请求体
            int len = msg.content().readableBytes();
            if (len > 0) {
                byte[] content = new byte[len];
                msg.content().readBytes(content);
                body = new String(content, "UTF-8");
            }

            //通过多线程线程池将处理结果返还
            HttpWorkerThread t = new HttpWorkerThread(
                    msg.getProtocolVersion(),
                    HttpHeaders.isKeepAlive(msg),
                    ctx.channel(),
                    param,
                    body,
                    op);
            httpExecutors.execute(t);

        }
    }
}